<?php
namespace We7\Installer\Console;


use Symfony\Component\Console\Question\ConfirmationQuestion;
use ZipArchive;
use RuntimeException;
use GuzzleHttp\Client;
use Symfony\Component\Process\Process;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Filesystem\Exception\IOExceptionInterface;
class NewCommand extends Command
{

	private $appSupport =  false;
	private $wxappSupport = false;
	private $name = '';
	/**
	 * Configure the command options.
	 *
	 * @return void
	 */
	protected function configure()
	{
		$this
			->setName('new')
			->setDescription('创建模块脚手架')
			->addArgument('name', InputArgument::REQUIRED, '模块标识')
			->addOption('force', null, InputOption::VALUE_NONE, '强制覆盖已有目录');
	}


	private function ask($input, $output, $question) {
		$helper = $this->getHelper('question');
		$question = new ConfirmationQuestion($question.'?', false);
		return $helper->ask($input, $output, $question);
	}

	protected function appSupport($input, $output) {
		$this->appSupport = $this->ask($input, $output, '是否支持公众号<app_support>');
	}

	protected function wxappSupport($input, $output) {
		$this->wxappSupport = $this->ask($input, $output, '是否支持小程序<wxapp_support>');
	}

	protected function pcSupport($input, $output) {
		$this->pcSupport = $this->ask($input, $output, '是否支持PC<pc_support>');
	}

	protected function systemWelcomeSupport($input, $output) {
		$this->systemWelcome_support = $this->ask($input, $output, '是否支持系统首页<systemWelcome_support>');
	}


	protected function supportAsk($input, $output) {
		$this->appSupport($input, $output);
		$this->wxappSupport($input, $output);
		$this->pcSupport($input, $output);
		$this->systemWelcomeSupport($input, $output);
	}

	/**
	 *  创建模块文件
	 */
	protected function createApp($input, $output) {
		if ($this->appSupport) {

		}
	}

	protected function createWxapp($input, OutputInterface $output) {
		if ($this->wxappSupport) {
			$filename = 'wxapp.php';
			$output->write('生成小程序后台文件wxapp.php...');
			$this->writePhp('wxapp.php', $this->tpl('wxapp'));
		}
	}

	public function writePhp($filename, $content) {
		$content = str_replace('{module}', ucfirst($this->name), $content);
		file_put_contents($this->dir().'/'.$filename, $content);
	}

	protected function dir() {
		return $this->directory;
	}

	public function tpl($filename) {

		return file_get_contents(__DIR__.'/../tpl/'.$filename.'.tpl');
	}

	protected function create($input, $output) {
		$this->createApp($input, $output);
		$this->createWxapp($input, $output);
	}
	/**
	 * Execute the command.
	 *
	 * @param  \Symfony\Component\Console\Input\InputInterface  $input
	 * @param  \Symfony\Component\Console\Output\OutputInterface  $output
	 * @return void
	 */
	protected function execute(InputInterface $input, OutputInterface $output)
	{
		if (! class_exists('ZipArchive')) {
			throw new RuntimeException('The Zip PHP extension is not installed. Please install it and try again.');
		}
		$this->name = $input->getArgument('name');
		$directory = ($input->getArgument('name')) ? getcwd().'/'.$input->getArgument('name') : getcwd();
		if (! $input->getOption('force')) {
			$this->verifyApplicationDoesntExist($directory);
		}
		$this->directory = $directory;
		$output->writeln('<info>开始创建模块<start create module>...</info>');
		$this->supportAsk($input, $output);
		$this->create($input, $output);

//		$version = $this->getVersion($input);
//		$this->download($zipFile = $this->makeFilename(), $version)
//			->extract($zipFile, $directory)
//			->prepareWritableDirectories($directory, $output)
//			->cleanUp($zipFile);
//		$composer = $this->findComposer();
//		$commands = [
//			$composer.' install --no-scripts',
//			$composer.' run-script post-root-package-install',
//			$composer.' run-script post-create-project-cmd',
//			$composer.' run-script post-autoload-dump',
//		];
//		if ($input->getOption('no-ansi')) {
//			$commands = array_map(function ($value) {
//				return $value.' --no-ansi';
//			}, $commands);
//		}
//		$process = new Process(implode(' && ', $commands), $directory, null, null, null);
//		if ('\\' !== DIRECTORY_SEPARATOR && file_exists('/dev/tty') && is_readable('/dev/tty')) {
//			$process->setTty(true);
//		}
//		$process->run(function ($type, $line) use ($output) {
//			$output->write($line);
//		});
		$output->writeln('<comment>Application ready! Build something amazing.</comment>');
	}
	/**
	 * Verify that the application does not already exist.
	 *
	 * @param  string  $directory
	 * @return void
	 */
	protected function verifyApplicationDoesntExist($directory)
	{

		if ((is_dir($directory) || is_file($directory)) && $directory != getcwd()) {
//			throw new RuntimeException('应用已存在!');
		}
	}
	/**
	 * Generate a random temporary filename.
	 *
	 * @return string
	 */
	protected function makeFilename()
	{
		return getcwd().'/laravel_'.md5(time().uniqid()).'.zip';
	}

	/**
	 * Extract the Zip file into the given directory.
	 *
	 * @param  string  $zipFile
	 * @param  string  $directory
	 * @return $this
	 */
	protected function extract($zipFile, $directory)
	{
		$archive = new ZipArchive;
		$archive->open($zipFile);
		$archive->extractTo($directory);
		$archive->close();
		return $this;
	}
	/**
	 * Clean-up the Zip file.
	 *
	 * @param  string  $zipFile
	 * @return $this
	 */
	protected function cleanUp($zipFile)
	{
		@chmod($zipFile, 0777);
		@unlink($zipFile);
		return $this;
	}
	/**
	 * Make sure the storage and bootstrap cache directories are writable.
	 *
	 * @param  string  $appDirectory
	 * @param  \Symfony\Component\Console\Output\OutputInterface  $output
	 * @return $this
	 */
	protected function prepareWritableDirectories($appDirectory, OutputInterface $output)
	{
		$filesystem = new Filesystem;
		try {
			$filesystem->chmod($appDirectory.DIRECTORY_SEPARATOR."bootstrap/cache", 0755, 0000, true);
			$filesystem->chmod($appDirectory.DIRECTORY_SEPARATOR."storage", 0755, 0000, true);
		} catch (IOExceptionInterface $e) {
			$output->writeln('<comment>You should verify that the "storage" and "bootstrap/cache" directories are writable.</comment>');
		}
		return $this;
	}
	/**
	 * Get the version that should be downloaded.
	 *
	 * @param  \Symfony\Component\Console\Input\InputInterface  $input
	 * @return string
	 */
	protected function getVersion(InputInterface $input)
	{
		if ($input->getOption('dev')) {
			return 'develop';
		}
		return 'master';
	}
	/**
	 * Get the composer command for the environment.
	 *
	 * @return string
	 */
	protected function findComposer()
	{
		if (file_exists(getcwd().'/composer.phar')) {
			return '"'.PHP_BINARY.'" composer.phar';
		}
		return 'composer';
	}
}